package net.kingborn.erp.bc.command;

import net.kingborn.core.command.BaseCommand;
import net.kingborn.core.command.Command;
import net.kingborn.core.command.Param;
import net.kingborn.core.exception.Assert;
import net.kingborn.core.exception.BizException;
import net.kingborn.core.util.StrKit;
import net.kingborn.erp.bc.model.*;
import net.kingborn.erp.bc.service.SellAccountService;
import net.kingborn.erp.bc.service.SellProductService;
import net.kingborn.erp.bc.service.SellService;
import net.kingborn.erp.uc.model.*;
import net.kingborn.erp.uc.service.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 销货单保存
 */
@Command
public class CSellSave extends BaseCommand {

    @Autowired
    private SellService sellService;
    @Autowired
    private SellProductService sellProductService;
    @Autowired
    private SettlementAccountService settlementAccountService;
    @Autowired
    private ProductService productService;
    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private SellAccountService sellAccountService;

    @Param(required = true)
    private Sell sell;
    @Param(defaultValue = "[]")
    private List<SellProduct> productList;
    @Param(defaultValue = "[]")
    private List<SellAccount> accountList;

    private Sell persistedSell;
    
    @Override
    protected void init() throws Exception {

    }

    @Override
    protected void doCommand() throws Exception {
        // 校验数据
        Assert.notBlank(sell.getCustomerId(), "客户ID不能为空！");
        Customer customer = customerService.getById(sell.getCustomerId());
        Assert.notNull(customer, "ID为【" + sell.getCustomerId() + "】的客户不存在！");

        Assert.notBlank(sell.getSellerId(), "销售ID不能为空！");
        Employee seller = employeeService.getById(sell.getSellerId());
        Assert.notNull(seller, "ID为【" + sell.getSellerId() + "】的用户不存在！");

        // 计算
        if (StrKit.isBlank(sell.getId())) {
            persistedSell = new Sell();

            // 校验编码是否合法
            validateCode(sell.getCode());
            persistedSell.setCode(sell.getCode());
            persistedSell.setChecked(false);

        } else {
            persistedSell = sellService.getById(sell.getId());
            Assert.notNull(persistedSell, "ID为【" + sell.getId() + "】的销货订单不存在！");

            // 删除原来的商品
            sellProductService.deleteBySell(sell.getId());
        }

        persistedSell.setIssueDate(sell.getIssueDate());
        persistedSell.setCustomerId(sell.getCustomerId());
        persistedSell.setSellerId(sell.getSellerId());
        persistedSell.setContactName(sell.getContactName());
        persistedSell.setAddress(sell.getAddress());
        persistedSell.setPhone(sell.getPhone());
        persistedSell.setDiscountAmount(sell.getDiscountAmount());
        persistedSell.setDiscountedAmount(sell.getDiscountedAmount());
        persistedSell.setQuantity(getQuantity());
        persistedSell.setDiscountRate(sell.getDiscountRate());
        persistedSell.setCustomerFee(sell.getCustomerFee());
        persistedSell.setCollectedAmount(sell.getCollectedAmount());
        persistedSell.setDebtAmount(sell.getDebtAmount());
        persistedSell.setAttachments(sell.getAttachments());
        persistedSell.setListerId(sell.getListerId());
        persistedSell.setRemark(sell.getRemark());
        sellService.saveOrUpdate(persistedSell);

        // 新增商品
        addProductList();

        // 新增账户
        addAccountList();

        data.put("sell", persistedSell);
    }

    /**
     * 新增账户列表
     */
    private void addAccountList() {
        if (accountList == null || accountList.size() == 0) return;

        List<SellAccount> persistedSellAccountList = new ArrayList<>();
        SellAccount persistedSellAccount;
        for (SellAccount sellAccount : accountList) {
            Assert.notBlank(sellAccount.getAccountId(), "结算账户的ID不能为空！");
            SettlementAccount settlementAccount = settlementAccountService.getById(sellAccount.getAccountId());
            Assert.notNull(settlementAccount, "ID为【" + sellAccount.getAccountId() + "】的结算账户不存在！");

            persistedSellAccount = new SellAccount();
            persistedSellAccount.setSellId(persistedSell.getId());
            persistedSellAccount.setAccountId(sellAccount.getAccountId());

            // TODO 校验金额
            persistedSellAccount.setPaidAmount(sellAccount.getPaidAmount());

            persistedSellAccountList.add(persistedSellAccount);
        }

        sellAccountService.saveBatch(persistedSellAccountList);
    }

    /**
     * 校验单据编号是否合法
     *
     * @param code
     */
    private void validateCode(String code) {
        Sell sell = sellService.findByCode(code);
        if (sell != null) {
            throw new BizException("单据编号为【" + code + "】的销货单已经存在！");
        }
    }

    /**
     * 获取总数量
     *
     * @return
     */
    private Double getQuantity() {
        double quantity = 0.0d;
        for (SellProduct product : productList) {
            quantity += product.getQuantity();
        }

        return quantity;
    }

    /**
     * 新增商品列表
     */
    private void addProductList() {
        if (productList == null || productList.size() == 0) return;

        List<SellProduct> persistedSellProductList = new ArrayList<>();
        SellProduct persistedSellProduct;
        for (SellProduct sellProduct : productList) {
            Assert.notBlank(sellProduct.getProductId(), "商品ID不能为空！");
            Product product = productService.getById(sellProduct.getProductId());
            Assert.notNull(product, "ID为【" + sellProduct.getProductId() + "】的商品不存在！");


            Assert.notBlank(sellProduct.getWarehouseId(), "仓库ID不能为空！");
            Warehouse warehouse = warehouseService.getById(sellProduct.getWarehouseId());
            Assert.notNull(warehouse, "ID为【" + sellProduct.getWarehouseId() + "】的仓库不存在！");

            persistedSellProduct = new SellProduct();
            persistedSellProduct.setSellId(persistedSell.getId());
            persistedSellProduct.setProductId(product.getId());
            persistedSellProduct.setWarehouseId(warehouse.getId());

            // TODO 校验数据
            persistedSellProduct.setQuantity(sellProduct.getQuantity());
            persistedSellProduct.setPrice(sellProduct.getPrice());
            persistedSellProduct.setDiscountRate(sellProduct.getDiscountRate());
            persistedSellProduct.setDiscountAmount(sellProduct.getDiscountAmount());
            persistedSellProduct.setAmount(sellProduct.getAmount());
            persistedSellProduct.setCode(sellProduct.getCode());
            persistedSellProduct.setRemark(sellProduct.getRemark());

            persistedSellProductList.add(persistedSellProduct);
        }

        sellProductService.saveBatch(persistedSellProductList);
    }
}
